package com.lwx.mongo;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

public class MongoManager {
    private DB db;
    public MongoManager() {
        try {
            MongoCredential credential =
                    MongoCredential
                            .createMongoCRCredential("lwx522", "lwxDB", "88101053".toCharArray());
            MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("10.128.175.248", 27017)),
                    Arrays.asList(credential));
            this.db = mongoClient.getDB("lwxDB");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
    
    public void insert(String tableName, DBObject ... doc){
        db.getCollection(tableName).insert(doc);
    }
    
    public void insert(String tableName, List<DBObject> list ){
        db.getCollection(tableName).insert(list);
    }
    
    public List<DBObject> find(String tableName){
        List<DBObject> dbObjects = new ArrayList<>();
        DBCursor dBCursor = db.getCollection(tableName).find();
        while(dBCursor.hasNext()){
            dbObjects.add(dBCursor.next());
        }
        return dbObjects;
    }
    
    public List<DBObject> find(String tableName, DBObject doc){
        List<DBObject> dbObjects = new ArrayList<>();
        DBCursor dBCursor = db.getCollection(tableName).find(doc);
        while(dBCursor.hasNext()){
            dbObjects.add(dBCursor.next());
        }
        return dbObjects;
    }    
    
    public void delete(String tableName, DBObject doc){
        db.getCollection(tableName).remove(doc);
    }
}
